import { defineStore } from 'pinia'

import { useRouter } from 'vue-router'
import { ref, onMounted, watch, computed } from 'vue'
import {
  getCityByIp,
  getAdcodeByCity,
  getLivesWeatherByAdcode,
  getForecastWeatherByAdcode,
} from '@/api/weatherAndCity'

export const useWeatherStore = defineStore('weather', () => {
  const localCity = ref(null)
  const selectedCity = ref(null)
  const adcode = ref(null)
  const livesWeather = ref(null)
  const forecastWeather = ref(null)
  const topHeaderLivesWeather = ref(null)
  const isLoaded = ref(false)
  const showAddIcon = ref(false)
  const followedCitiesWithTemp = ref([])
  const aboutFlag = ref(false)

  const router = useRouter()

  const fetchWeatherData = async (city) => {
    const { districts } = await getAdcodeByCity(city)
    adcode.value = districts[0].adcode
    livesWeather.value = (await getLivesWeatherByAdcode(adcode.value)).lives[0]
    forecastWeather.value = (await getForecastWeatherByAdcode(adcode.value)).forecasts[0].casts
  }

  onMounted(async () => {
    const { city, adcode: ipAdcode } = await getCityByIp()
    localCity.value = city
    selectedCity.value = city
    adcode.value = ipAdcode
    await fetchWeatherData(city)
    topHeaderLivesWeather.value = (await getLivesWeatherByAdcode(ipAdcode)).lives[0]
    await loadFollowedCitiesWithTemp()
    isLoaded.value = true
  })

  const checkIfCityIsFollowed = (adcode) => {
    const storedCities = localStorage.getItem('followedCities')
    if (!storedCities) return false // 如果没有存储数据，直接返回 false
    const followedCities = JSON.parse(storedCities)
    return followedCities.some((city) => city.adcode === adcode)
  }

  watch(
    () => router.currentRoute.value,
    async (route) => {
      if (route.path === '/') {
        selectedCity.value = localCity.value
        await fetchWeatherData(localCity.value)
        showAddIcon.value = false // 回到首页时，隐藏添加图标
      } else if (route.name === 'search') {
        const { search } = route.query
        const { AdCode } = route.params
        selectedCity.value = search
        await fetchWeatherData(selectedCity.value)

        // 检查当前城市是否已经存在于 followedCities 中
        const isCityFollowed = checkIfCityIsFollowed(AdCode)
        showAddIcon.value = !isCityFollowed // 如果城市未关注，则显示添加图标
      }
      // 当路由变化时，调用loadFollowedCitiesWithTemp更新followedCitiesWithTemp
      await loadFollowedCitiesWithTemp()
    }
  )

  const addCity = () => {
    const { AdCode } = router.currentRoute.value.params
    const { search } = router.currentRoute.value.query
    const newCityData = {
      city: search,
      adcode: AdCode,
    }
    let existingCities = []
    const storedCities = localStorage.getItem('followedCities')
    existingCities = JSON.parse(storedCities) || []
    existingCities.push(newCityData)
    localStorage.setItem('followedCities', JSON.stringify(existingCities))
    showAddIcon.value = false // 添加城市到本地储存后，隐藏添加图标
  }

  const deleteCity = (adcodeToDelete) => {
    const storedCities = localStorage.getItem('followedCities')
    if (storedCities) {
      let followedCities = JSON.parse(storedCities)
      followedCities = followedCities.filter((city) => city.adcode !== adcodeToDelete)
      localStorage.setItem('followedCities', JSON.stringify(followedCities))
      // 更新followedCitiesWithTemp
      followedCitiesWithTemp.value = followedCitiesWithTemp.value.filter(
        (city) => city.adcode !== adcodeToDelete
      )
    }
  }

  const weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  const weatherInfoTop = computed(() => {
    return forecastWeather.value.map((item, index) => {
      let weekText
      if (index === 0) {
        weekText = '今天'
      } else if (index === 1) {
        weekText = '明天'
      } else {
        weekText = weeks[item.week - 1]
      }
      return {
        week: weekText,
        date: item.date.slice(5),
        weather: item.dayweather,
        wind: '风力 ' + item.daypower + '级',
      }
    })
  })

  const dayTempArr = computed(() => {
    return forecastWeather.value.map((item) => parseFloat(item.daytemp_float))
  })

  const nightTempArr = computed(() => {
    return forecastWeather.value.map((item) => parseFloat(item.nighttemp_float))
  })

  const cities = ref([])
  const searchText = ref('')
  const ulStatus = ref('1') //将ulStatus初始化为 '1'，避免初始状态下显示网络错误提示
  const searchUlShow = ref(false) //初始状态下搜索框隐藏

  // 接收搜索城市的输入，并通过getAdcodeByCity得到cities
  const searchCity = async () => {
    cities.value = [] //新搜索开始时清空数组
    if (!searchText.value) {
      searchUlShow.value = false
      ulStatus.value = '1' // 清空搜索框时重置ulStatus,确保在下次搜索之前，提示信息处于初始状态，不会显示之前搜索可能产生的 “无城市结果” 或 “网络错误” 提示
      return
    }
    try {
      const { districts, status } = await getAdcodeByCity(searchText.value)
      cities.value = districts.map((item) => ({
        name: item.name,
        adcode: item.adcode,
      }))
      if (districts.length === 0 && status === '1') {
        ulStatus.value = 'noCityFound' // 无城市结果
      } else {
        ulStatus.value = status
      }
    } catch (error) {
      ulStatus.value = 'networkError' // 网络错误
    }
    searchUlShow.value = cities.length > 0 || ulStatus !== '1'
  }

  watch(selectedCity, async (newCity) => {
    await fetchWeatherData(newCity)
  })

  const loadFollowedCitiesWithTemp = async () => {
    const storedCities = localStorage.getItem('followedCities')
    if (storedCities) {
      const followedCities = JSON.parse(storedCities)
      const citiesWithTempPromises = followedCities.map(async (city) => {
        const liveWeather = await getLivesWeatherByAdcode(city.adcode)
        return {
          ...city,
          temperature: liveWeather.lives[0].temperature,
        }
      })
      followedCitiesWithTemp.value = await Promise.all(citiesWithTempPromises)
    } else {
      followedCitiesWithTemp.value = []
    }
  }

  return {
    localCity,
    selectedCity,
    livesWeather,
    topHeaderLivesWeather,
    isLoaded,
    weatherInfoTop,
    dayTempArr,
    nightTempArr,
    searchText,
    cities,
    ulStatus,
    searchCity,
    searchUlShow,
    addCity,
    showAddIcon,
    followedCitiesWithTemp,
    deleteCity,
    aboutFlag,
  }
})
